package com.imooc.utils;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.imooc.excel.ExcelVO;
import com.wuwenze.poi.ExcelKit;
import com.wuwenze.poi.handler.ExcelReadHandler;
import com.wuwenze.poi.pojo.ExcelErrorField;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 导入
 *
 * @author 顾志杰
 * @date 2021/1/25-0:04
 */
public class ImportUtil {

    public static Map<String, Object> excelImport(MultipartFile file) throws IOException {
        final List<ExcelVO> data = Lists.newArrayList();
        final List<Map<String, Object>> error = Lists.newArrayList();
        ExcelKit.$Import(ExcelVO.class).readXlsx(file.getInputStream(), new ExcelReadHandler<ExcelVO>() {
            @Override
            public void onSuccess(int sheetIndex, int rowIndex, ExcelVO entity) {
                //第一页的数据
                if (sheetIndex == 0 && rowIndex > 2) {
                    List<ExcelErrorField> errorFields = new ArrayList<>();
                    ExcelVO one = new ExcelVO();

                    if (StringUtils.isBlank(entity.getRemark())) {
                        ExcelErrorField excelErrorField = new ExcelErrorField();
                        excelErrorField.setErrorMessage("备注不能为空");
                        excelErrorField.setColumn("备注");
                        errorFields.add(excelErrorField);
                    } else {
                        one.setRemark(entity.getRemark());
                    }

                    if (errorFields.size() > 0) {
                        error.add(ImmutableMap.of("row", rowIndex + 1, "errorFields", errorFields));
                    }
                    data.add(one);
                }
            }

            @Override
            public void onError(int sheet, int row, List<ExcelErrorField> errorFields) {
                if (sheet == 0 && row > 2) {
                    error.add(ImmutableMap.of("row", row + 1, "errorFields", errorFields));
                }
            }
        });
        Map<String, Object> map = new HashMap<>();
        map.put("error", error);
        map.put("data", data);
        return map;
    }

}
